package com.captain.controller;

import com.captain.common.Result;
import com.captain.entity.po.User;
import com.captain.service.UserService;
import com.captain.utils.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/user/set")
    public String setting(){
        return "user/set";
    }

    @GetMapping("/user/index")
    public String index(){
        return "user/index";
    }

    @PostMapping("/user/avatar/upload")
    @ResponseBody
    public Result uploadAvatar(MultipartFile file){
        //保存头像
        String savePath= FileUpload.saveAvatar(file);
        if(savePath==null){
            return Result.fail("头像保存失败");
        }else{
            HashMap<String,String> map=new HashMap<>();
            map.put("url",savePath);
            return Result.success("上传成功",map).setAction("/");
        }
    }

    @PostMapping("/user/set/update")
    @ResponseBody
    public Result updateUser(HttpServletRequest req,User user){
        User sessionUser=(User)req.getSession().getAttribute("user");
        //赋值id
        user.setId(sessionUser.getId());
        if(userService.updateUserSelective(user)>0){
            //更新session中的user
            User newSessionUser=userService.getUserById(sessionUser.getId());
            req.getSession().setAttribute("user",newSessionUser);
            //返回结果
            return Result.success("修改成功",null).setAction("/");
        }else{
            return Result.fail("修改失败");
        }
    }

    @GetMapping("/user/home")
    public String home(){
        return "user/home";
    }

    @GetMapping("/user/message")
    public String message(){
        return "user/message";
    }
}
